<template>
  <div class="addCoupon">
    <div class="content">
      <el-form
        ref="ruleFormRef"
        :model="params"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
        ><el-form-item label="优惠卷类型" prop="type">
          <el-select v-model="params.type" placeholder="请输入优惠卷类型">
            <el-option label="全场赠卷" :value="0" />
            <el-option label="会员赠卷" :value="1" />
            <el-option label="购物赠卷" :value="2" />
            <el-option label="注册赠卷" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="优惠卷名称" prop="name">
          <el-input v-model="params.name" placeholder="请输入优惠卷名称" />
        </el-form-item>
        <el-form-item label="适用平台" prop="platform">
          <el-select v-model="params.platform" placeholder="请输入优惠卷类型">
            <el-option label="全平台" :value="0" />
            <el-option label="移动平台" :value="1" />
            <el-option label="pc平台" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="总发行数" prop="publishCount">
          <el-input
            v-model="params.publishCount"
            placeholder="只能输入正整数"
          />
        </el-form-item>
        <el-form-item label="面额" prop="amount">
          <el-input
            v-model.number="params.amount"
            placeholder="面值只能是数值，限两位小数"
          >
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="每人限领" prop="perLimit">
          <el-input v-model="params.perLimit">
            <template #append>张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="使用门槛" prop="minPoint">
          <el-input v-model="params.minPoint" placeholder="只能输入正整数">
            <template #prepend>满</template>
            <template #append>元可用</template>
          </el-input>
        </el-form-item>
        <el-form-item label="领取日期" prop="enableTime">
          <el-date-picker
            v-model="params.enableTime"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="有效期">
          <el-date-picker
            v-model="params.startTime"
            type="date"
            placeholder="选择日期"
          />至
          <el-date-picker
            v-model="params.endTime"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="可使用商品" prop="useType">
          <el-radio-group v-model="useTypeNumber">
            <el-radio-button :label="0">全场通用</el-radio-button>
            <el-radio-button :label="1">指定分类</el-radio-button>
            <el-radio-button :label="2">指定商品</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input
            v-model="params.note"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            提交
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import { ApiAddCoupon, ApiUpdateCoupon } from "./api";
import { useRouter, useRoute } from "vue-router";
import { reactive, ref, watch } from "vue";
import { ApiCouponItemById } from "./api";

// 路由
const router = useRouter();
const route = useRoute();

// 请求参数
const params = ref<IAddParams>({
  type: 0,
  platform: 0,
  perLimit: 1,
  useType: 0,
});

// 监听id
watch(
  () => route.query.id,
  () => {
    if (route.query.id) {
      ApiCouponItemById(parseInt(route.query.id as string)).then((res) => {
        if (res.code == 200) {
          params.value = res.data;
        } else {
          ruleFormRef.value?.resetFields();
        }
      });
    }
  },
  {
    immediate: true,
  }
);

const useType = ref("全场通用");
const useTypeNumber = ref(0);

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();

// 验证是否为正整数
const isInteger = (rule: any, value: any, callback: (i?: any) => any) => {
  if (!value) {
    callback(new Error("请输入"));
  } else if (!/(^[1-9]\d*$)/.test(value)) {
    callback(new Error("请输入正整数"));
  } else {
    callback();
  }
};

// 验证面额
let quantityScale = "2";
let re = new RegExp("^(0|[1-9][0-9]*)(\\.[0-9]{0," + quantityScale + "})?$");
const isAmount = (rule: any, value: any, callback: (i?: any) => any) => {
  if (!value) {
    callback(new Error("请输入面额"));
  } else if (!/(^[1-9]\d*$)/.test(value)) {
    callback(new Error("请输入数字"));
  } else {
    callback();
  }
};

// 校验规则
const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入优惠卷名称", trigger: "blur" }],
  publishCount: [
    {
      required: true,
      trigger: "blur",
      validator: isInteger,
    },
  ],
  amount: [
    {
      required: true,
      trigger: "blur",
      validator: isAmount,
    },
  ],
  minPoint: [
    {
      required: true,
      validator: isInteger,
      trigger: "change",
    },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  // if (useType.value == "全场通用") {
  //   params.value.useType = 0;
  // } else if (useType.value == "指定分类") {
  //   params.value.useType = 1;
  // } else {
  //   params.value.useType = 2;
  // }
  params.value.useType = useTypeNumber.value;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("你确定添加此优惠卷吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          if (!route.query.id) {
            ApiAddCoupon(params.value).then((res) => {
              if (res.code !== 200) return;
              ElMessage.success("添加成功");
              router.push("/sms/coupon");
            });
          } else {
            ApiUpdateCoupon(
              parseInt(route.query.id as string),
              params.value
            ).then((res) => {
              if (res.code == 200) {
                ElMessage.success("修改成功");
                router.push("/sms/coupon");
              }
            });
          }
        })
        .catch(() => {});
    } else {
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));
</script>

<style lang="less" scoped>
.addCoupon {
  display: flex;
  justify-content: center;
  align-items: center;
  .content {
    border: 1px solid #eee;
    width: 600px;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
  }
}
</style>
